from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from loguru import logger
from uuid import uuid4

from myPsycho import main_psycho
from myDSM import main_dsm
from myProfile import main_profile
from myClinic import main_clinic

app = FastAPI()

logger.add("info.log", format="Log: [{extra[log_id]}: {time} - {level} - \
           {message} ", level="INFO", enqueue=True)


@app.middleware("http")
async def log_middleware(request: Request, call_next):
    log_id = str(uuid4())
    with logger.contextualize(log_id=log_id):
        logger.info('Request to access ' + request.url.path)
        try:
            response = await call_next(request)
        except Exception as ex:
            logger.error("Request to " + request.url.path + f" failed: {ex}")
            response = JSONResponse(content={"success": False},
                                    status_code=500)
        finally:
            logger.info('Successfully accessed ' + request.url.path)
            return response

app.mount("/openpsycho/psycho", main_psycho.psycho_app)
app.mount("/openpsycho/dsm", main_dsm.dsm_app)
app.mount("/openpsycho/profile", main_profile.profile_app)
app.mount("/openpsycho/clinic", main_clinic.clinic_app)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/index")
async def root():
    return {"message": "Welcome to OpenPsychology!"}
